package cn.edu.whut.gateway.util;

import cn.edu.whut.gateway.error.UnauthorizedException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    private final JWTSigner jwtSigner;

    public JwtUtil(KeyPair keyPair){
        this.jwtSigner = JWTSignerUtil.createSigner("rs256", keyPair);
    }

    /**
     * 创建token
     *
     * @param userId 用户id
     * @param tenantId 租户id
     * @param ttl token过期时间
     * @return token
     */
    public String createToken(Integer userId, Integer tenantId, Duration ttl){
        Map<String, Integer> payloadData = new HashMap<>();
        payloadData.put("userId", userId);
        payloadData.put("tenantId", tenantId);
        return JWT.create()
                .setPayload("user", payloadData)
                .setExpiresAt(new Date(System.currentTimeMillis() + ttl.toMillis()))
                .setSigner(jwtSigner)
                .sign();
    }

    /**
     * 解析token
     * @param token token
     * @return 用户id和租户id
     */
    public Map<String, Integer> parseToken(String token) {
        if (token == null) {
            throw new UnauthorizedException("用户未登录");
        }
        JWT jwt;
        try {
            jwt = JWT.of(token).setSigner(jwtSigner);
        } catch (Exception e) {
            throw new UnauthorizedException("无效的token", e);
        }
        // 验证token是否有效
        if (!jwt.verify()) {
            throw new UnauthorizedException("无效的token");
        }
        try {
            JWTValidator.of(jwt).validateDate();
        } catch (Exception e) {
            throw new UnauthorizedException("token已过期");
        }
        Object userPayloadData = jwt.getPayload("user");
        if (userPayloadData == null) {
            throw new UnauthorizedException("无效的token");
        }else{
            return (Map<String, Integer>) jwt.getPayload("user");
        }
    }
}
